package fm.yichenet.mongo.service.impl;

import com.mongodb.BasicDBObject;
import com.mongodb.DBObject;
import fm.cache.GoodClassCache;
import fm.config.MainConfig;
import fm.dao.MongoBaseDao;
import fm.dto.NeiyiUser;
import fm.mongo.MCondition;
import fm.mongo.MRel;
import fm.mongo.MongoTable;
import fm.mongoService.UserService;
import fm.util.CommonUtils;
import fm.util.DateUtils;
import fm.web.CurrentRequest;
import fm.yichenet.mongo.service.GoodMgrService;
import fm.yichenet.mongo.service.VisitHistoryService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.codec.Base64;
import org.apache.shiro.crypto.AesCipherService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by CM on 2017/7/30.
 */
@Service
public class VisitHistoryServiceImpl implements VisitHistoryService {
    private static final Logger LOGGER = LoggerFactory.getLogger(VisitHistoryService.class);
    @Autowired
    MongoBaseDao mongoBaseDao;
    @Autowired
    GoodMgrService goodMgrService;
    @Autowired
    UserService userService;

    @Override
    public void addVisitLog(DBObject log) throws Exception {
        mongoBaseDao.insert(log, MongoTable.good_visit_log);
    }

    @Override
    public List getLikeGoodListOfVisitLog(Integer pageNum, Integer pageSize) throws Exception {
        NeiyiUser user = null;
        try {
            String token = CurrentRequest.getRequest().getParameter("token");
            if (StringUtils.isNotEmpty(token)) {
                token = token.replaceAll("-", "+").replaceAll("\\*", "/");
                LOGGER.info("替换字符后token :{}", token);
                AesCipherService aesCipherService = new AesCipherService();
                byte[] decodeData = aesCipherService.decrypt(Base64.decode(token), Base64.decode(MainConfig.tokenAesKey.getBytes())).getBytes();
                String tokenDecode = new String(decodeData);
                String unionId = tokenDecode.substring(20, tokenDecode.length());
                LOGGER.info("token解码后获得UNION_ID:{}", unionId);
                user = userService.getUserByUnionid(unionId);
                if (CommonUtils.isEmpty(user)) {
                    LOGGER.info("获取用户信息失败:{}", user.getName());

                }
            }
        } catch (Exception ex) {
            LOGGER.info("未登录用户,无法推荐商品", ex);
        }
        if (user != null) {
            //三个月内有浏览的数据
            MCondition mc = MCondition.create(MRel.and);
            mc.append("user_id", user.getId());
            mc.append(MCondition.create(MRel.gte).append("visit_time", DateUtils.addMonth(new Date(), -3)));

            List<DBObject> logs = (List<DBObject>) mongoBaseDao.getList(mc.toDBObject().toMap(), DBObject.class,
                    MongoTable.good_visit_log, new BasicDBObject("visit_time", Sort.Direction.DESC.toString()));
            if (CollectionUtils.isNotEmpty(logs)) {
                //有浏览记录的 才取用
                MCondition allMc = MCondition.create(MRel.and);
                MCondition queryMc = MCondition.create(MRel.or);
                allMc.append("status", 1 + "");
                for (DBObject logItem : logs) {
                    if (logItem.containsField("keyword")) {
                        queryMc.append(MCondition.create(MRel.regex).append("goodName", logItem.get("keyword")));
                    }
                    if (logItem.containsField("good_class_id")) {
                        queryMc.append("good_class_id", logItem.get("good_class_id"));
                    }
                    if (logItem.containsField("bigType")) {
                        queryMc.append("bigType", logItem.get("bigType"));
                    }
                    if (logItem.containsField("shop_id")) {
                        queryMc.append("shop_id", logItem.get("shop_id"));
                    }
                }
                allMc.append(queryMc);

                LOGGER.info("猜你喜欢推荐查询条件:{}", allMc.toDBObject().toString());

                List result = (List) mongoBaseDao.getPageList(allMc.toDBObject().toMap(), DBObject.class, pageSize, pageNum,
                        MongoTable.good_visit_log, new BasicDBObject("priority", Sort.Direction.DESC.toString()));
                if (CollectionUtils.isNotEmpty(result)) {
                    for (Object item : result) {
                        DBObject object = (DBObject) item;
                        Long goodClassId = Long.parseLong("" + object.get("good_class_id"));
                        //TODO 商品价格是否显示为0 要根据类别是否开启了隐藏价格 如果开启了此属性，该类商品的价格全部显示为零 ，订单流程也要按照待改价的商品来处理
                        if (GoodClassCache.isHidePrice(goodClassId)) {
                            object.put("sale_price", 0);
                            object.put("source_price", 0);
                        }
                    }
                    return result;
                }
            }
        }
        LOGGER.info("信息不足，随机获取10个商品猜你喜欢");
        //未登录的用户随意查询10条最新的商品
        Map param = new HashMap();
        param.put("status", 1 + "");
        return goodMgrService.getList(param, 1, 10, null);

    }
}
